package com.ruoyi.gpt.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.core.config.utils.WxGptUtil;
import com.ruoyi.gpt.domain.SignIn;
import com.ruoyi.gpt.domain.bo.GptUserBo;
import com.ruoyi.gpt.domain.vo.GptUserVo;
import com.ruoyi.gpt.service.IGptUserService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gpt.domain.vo.SignInVo;
import com.ruoyi.gpt.domain.bo.SignInBo;
import com.ruoyi.gpt.service.ISignInService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * chatGpt用户每日签到
 *
 * @author ztx
 * @date 2023-04-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/gpt/signIn")
public class SignInController extends BaseController {

    private final ISignInService iSignInService;
    private final IGptUserService iGptUserService;

    /**
     * 查询chatGpt用户每日签到列表
     */
    @SaCheckPermission("gpt:signIn:list")
    @GetMapping("/list")
    public TableDataInfo<SignInVo> list(SignInBo bo, PageQuery pageQuery) {
        return iSignInService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出chatGpt用户每日签到列表
     */
    @SaCheckPermission("gpt:signIn:export")
    @Log(title = "chatGpt用户每日签到", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SignInBo bo, HttpServletResponse response) {
        List<SignInVo> list = iSignInService.queryList(bo);
        ExcelUtil.exportExcel(list, "chatGpt用户每日签到", SignInVo.class, response);
    }

    /**
     * 获取chatGpt用户每日签到详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("gpt:signIn:query")
    @GetMapping("/{id}")
    public R<SignInVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iSignInService.queryById(id));
    }

    /**
     * 新增chatGpt用户每日签到
     */
    @SaCheckPermission("gpt:signIn:add")
    @Log(title = "chatGpt用户每日签到", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SignInBo bo) {
        return toAjax(iSignInService.insertByBo(bo));
    }

    /**
     * 修改chatGpt用户每日签到
     */
    @SaCheckPermission("gpt:signIn:edit")
    @Log(title = "chatGpt用户每日签到", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SignInBo bo) {
        return toAjax(iSignInService.updateByBo(bo));
    }

    /**
     * 删除chatGpt用户每日签到
     *
     * @param ids 主键串
     */
    @SaCheckPermission("gpt:signIn:remove")
    @Log(title = "chatGpt用户每日签到", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iSignInService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 查询当前登录用户的当日签到情况,是否已经签到
     */
    @GetMapping("/querySignIn")
    public R<HashMap<String, Boolean>> querySignIn() {
        Long userId = getUserId();
        SignIn signIn = iSignInService.querySignInByUserId(userId);
        HashMap<String, Boolean> result = new HashMap<String, Boolean>();
        if(ObjectUtil.isNull(signIn)){
            // 未查到该用户的签到记录就是，false
            result.put("isSignIn", false);
            return R.ok(result);
        }
        //查到了判断更新日期是不是今天 ,true表示重置为当日起始时间
        long betweenDays = DateUtil.betweenDay(signIn.getUpdateTime(), new Date(), true);
        if(betweenDays == 0){
            // 表示已经签到
            result.put("isSignIn", true);
        }else{
            // 表示今天未签到
            result.put("isSignIn", false);
        }
        return R.ok(result);
    }
    /**
     * 执行签到
     */
    @PostMapping("/addSignIn")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> addSignIn() {
        GptUserVo userVo = WxGptUtil.getUserVoByToken();
        if (ObjectUtil.isNull(userVo)) {
            return R.fail("请先登录");
        }
        // 获取用户剩余次数
        Integer gptRemaining = userVo.getGptRemaining();
        if(ObjectUtil.isNull(gptRemaining) || gptRemaining <= 0){
            gptRemaining = 0;
        }
        SignIn signIn = iSignInService.querySignInByUserId(userVo.getId());
        if(ObjectUtil.isNull(signIn)){
            // 未查到该用户的签到记录 添加签到记录
            signIn = new SignIn();
            signIn.setUserId(userVo.getId());
            signIn.setContinueDays(1);
            signIn.setUserName(userVo.getNickname());
            signIn.setUserNickname(userVo.getNickname());
            signIn.setTotalDays(1);
            iSignInService.insertByBo(BeanUtil.toBean(signIn, SignInBo.class));
            userVo.setGptRemaining( gptRemaining+ 5);
            // 更新用户信息
            iGptUserService.updateByBo(BeanUtil.toBean(userVo, GptUserBo.class));
            return R.ok("签到成功");
        }
        //有用户，判断更新日期是不是今天
        long betweenDays = DateUtil.betweenDay(signIn.getUpdateTime(), new Date(), true);
        boolean isSignSuccess = false;
        if(betweenDays == 0){
            // 表示已经签到
            return R.fail("今日已签到");
        }else {
            // 间隔不是0表示未签到
            if(betweenDays == 1){
                // 表示今天未签到,并且间隔天数是1天
                signIn.setContinueDays(signIn.getContinueDays() + 1);
                signIn.setTotalDays(signIn.getTotalDays() + 1);
            }else if(betweenDays > 1){
                // 表示今天未签到,并且间隔天数大于1天
                signIn.setContinueDays(1); // 连续天数重置为1
                signIn.setTotalDays(signIn.getTotalDays() + 1);
            }
            // 给用户添加调用次数

            userVo.setGptRemaining( gptRemaining+ 5);
            // 添加签到记录
            isSignSuccess = iSignInService.updateByBo(BeanUtil.toBean(signIn, SignInBo.class));
            // 更新用户信息
            iGptUserService.updateByBo(BeanUtil.toBean(userVo, GptUserBo.class));
        }

        return isSignSuccess ? R.ok("签到成功") : R.fail("签到失败");
    }
}
